package com.example.aop;

import com.example.mapper.operateLogMapper;
import com.example.models.logInfo;
import com.example.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Component
@Aspect
@Order(1)
@Slf4j
public class LogAspect {
    @Autowired
    private operateLogMapper operate;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JWTUtils JwtUtils;
    @Around("@annotation(com.example.anno.LogAspect)")
    public Object operateTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long begin = System.currentTimeMillis();
        log.info("aop Around环绕开始----");
        // 获取请求token
        String token = request.getHeader("token");
        // 解密token
        Claims claims = JwtUtils.ParseJWT(token);
        Integer operateUser =(Integer) claims.get("id");
        // 获取目标对象的类名
        String className = joinPoint.getTarget().getClass().getName();
        log.info("目标对象的类名:{}",className);
        // 获取目标方法的方法名
        String methodName = joinPoint.getSignature().getName();
        log.info("目标方法的方法名:{}",methodName);

        // 获取目标方法运行时传入的参数
        Object[] args = joinPoint.getArgs();
        log.info("目标方法运行时传入的参数:{}",args);

        // 获取目标方法运行后的返回值
        Object result = joinPoint.proceed();// 调用原始操作
        long end = System.currentTimeMillis();

        logInfo res = new logInfo(null,operateUser,null,(int) (end-begin),className,methodName,args.toString(),result.toString());
        log.info("目标方法运行后的返回值：{}",res.toString());
        log.info("---开始记录日志---");
        operate.insertLog(res);
        log.info("---日志记录结束---");
        return result;

    }
}

